<?php 
namespace Admin\Controller;
use Think\Controller;
class LoginController extends Controller{
	//登录页面
	public function index(){
		if(!empty($_SESSION['username'])) $this->redirect('Index/index');
		$this->display();
	}
	//注册
	public function reg(){
		$this->display();
	}
	//验证码
	public function verify(){
		ob_end_clean();
		$verify=new \Think\Verify();
		$verify->length=4;
		$verify->codeSet='0123456789';            // 验证码字符集合
		$verify->fontSize = 14;
		$verify->useNoise = false;
		$verify->useCurve = false;
		$verify->imageH = '32px';
		$verify->imageW = '88px';
		
		$verify->entry();
	}
	//生成图片
	public function watermark(){
		
		$text=I('text');
		// $text=1234;
		$getConfig = array('font' => '/alidata/www/wmstest/Public/font/msyh.ttf', //默认字体. 相对于脚本存放目录的相对路径.
                    'text'  => $text, // 默认文字.
                    'size' => 30,//字体大小
                    'rot'  => 0,  //旋转角度.
                    'pad'  => 0,  //填充.
                    'transparent' => 1, // 文字透明度.
                    'red'  => 208, //文字颜色
                    'grn'  => 208,
                    'blu'  => 208,
                    'bg_red' => 255, //背景颜色
                    'bg_grn' => 255,
                    'bg_blu' => 255,
	               );
		$img=new \Home\Extend\TextImage($getConfig);
		echo($img::draw());
		// die;
	}
	//总后台管理员登录
	public function admin_manage(){
			$admin=session('admin.admin');
			$admin_info=session('admin.admin_info');
			if(!empty($admin) and !empty($admin_info)){
				$warehouse_code=I('warehouse_code');
				$warehouse=M('Warehouse');
				$warehouse_info=$warehouse->where(array('warehouse_code'=>$warehouse_code))->find();
				if(!empty($warehouse_info)){
					session('warehouse_code',$warehouse_info['warehouse_code']);
					session('warehouse_name',$warehouse_info['name']);
					$this->db_config();
					$au=M('AuthUser',C('DB_PRS'),C('DB_DEPOT'));
					$uid=$au->where($map)->find();
					if(empty($uid)){
						$map_nickname['password']=$map['password'];
						$map_nickname['nick_name']=$username;
						$uid=$au->where($map_nickname)->find();
					}
					if(!$uid){
						$result['message']='登陆失败！';
						$result['status']=0;
						$this->ajaxReturn($result);
					}else{
						session('personnel_no',$uid['personnel_no']);
						session('username',$uid['username']);
						session('nick_name',$uid['nick_name']);
						session('uid',$uid['uid']);
						session('logintime',time());

						$result['message']='登陆成功！';
						$result['status']=1;
						$this->ajaxReturn($result);
					}
				}else{
					$this->ajaxReturn(array('status'=>0,'message'=>"没有此用户数据"));
				}
			}else{
				$this->ajaxReturn(array('status'=>0,'message'=>"没有权限"));
			}
	}
	//登录验证
	public function checkLogin(){
		$result=array();
    	$ck=A('CheckInput');

    	$code=$ck->in('验证码','verify','cnennumstr','',4,7);
    	$verify=new \Think\Verify();
    	
		$map_warehouse['name']=$ck->in('仓库名称','warehouse_name','cnennumstr','',2,15);
		$map['username']=$ck->in('用户名','name','cnennumstr','',5,20);	
		$map['password']=$ck->in('密码','pwd','password','',5,20);	
		$username=I('name','','trim');
		if(!$verify->check($code)){
    		$result['message']='验证码错误！请刷新再次输入。';
    		$result['status']=false;
    		$this->ajaxReturn($result);
    	}
		$data['lastlogintime']=$_SERVER['REQUEST_TIME'];
		$data['lastloginip']=get_client_ip();

		$admin=M('Warehouse');
		$warehouse_info=$admin->where($map_warehouse)->find();
		if(empty($warehouse_info)){
			$result['message']='没有此仓库！';
			$result['status']=false;
			$this->ajaxReturn($result);
		}
		if($warehouse_info['status']==0){
			$result['message']='正在审核！';
			$result['status']=false;
			$this->ajaxReturn($result);
		}
		if($warehouse_info['status']==2){
			$result['message']='未通过审核！';
			$result['status']=false;
			$this->ajaxReturn($result);
		}
		session('warehouse_code',$warehouse_info['warehouse_code']);
		session('warehouse_name',$warehouse_info['name']);
		session('warehouse_status',$warehouse_info['warehouse_status']);
		$this->db_config();
		$au=M('AuthUser',C('DB_PRS'),C('DB_DEPOT'));
		$uid=$au->where($map)->find();
		
		if(empty($uid)){
			$map_nickname['password']=$map['password'];
			$map_nickname['nick_name']=$username;
			$uid=$au->where($map_nickname)->find();
			if($uid){
				$au->where($map_nickname)->save($data);
			}
		}else{
			$au->where($map)->save($data);
		}
		// echo $admin->getlastsql();
		// die;
		if(!$uid){
			$result['message']='登陆失败！用户名或密码错误。';
			$result['status']=false;
			$this->ajaxReturn($result);
		}else{
			session('personnel_no',$uid['personnel_no']);
			session('username',$uid['username']);
			session('nick_name',$uid['nick_name']);
			$info=$admin->where($map)->save($data);
			
			if(false===$info){
				$result['message']='更新时间和ip出错';
				$result['status']=false;
				$this->ajaxReturn($result);
			}
			session('uid',$uid['uid']);
			session('logintime',$data['lastlogintime']);

			$result['message']='登陆成功！';
			$result['status']=true;
			$this->ajaxReturn($result);
		}
	}
	
	//注册验证
	public function checkReg(){
		$result=array();
    	$ck=A('CheckInput');

    	$code=$ck->in('验证码','verify','cnennumstr','',4,7);
    	$verify=new \Think\Verify();
    	if(!$verify->check($code)){
    		$result['message']='验证码错误！请刷新再次输入。';
    		$result['status']=false;
    		$this->ajaxReturn($result);
    	}

		$map['username']=$ck->in('手机号','name','cnennumstr','',5,15);	
		$username=I('name','','trim');
		$nick_name=I('nick_name','','trim');
		if($username==$nick_name){
			$result['message']='昵称不能与注册手机号相同';
    		$result['status']=false;
    		$this->ajaxReturn($result);
		}
		$data['name']=I('warehouse_name');	
		$data['nick_name']=I('nick_name','','trim');
		$data['warehouse_code']=I('warehouse_code');	
		$data['password']=$ck->in('密码','pwd','password','',5,20);	
		$data['lastlogintime']=$_SERVER['REQUEST_TIME'];
		$data['lastloginip']=get_client_ip();
		$data['warehouse_status']=I('warehouse_status');
		
		$warehouse_cate=I('warehouse_cate');
		if($data['warehouse_status']==1){
			if(!$warehouse_cate){
				$return['status']=false;
				$return['message']="未选择仓库类型";
				$this->ajaxReturn($return);
			}
		}
		
		$data['warehouse_cate']=$warehouse_cate;
		$data['department_id']=$warehouse_cate;//角色id
		$admin=M('Warehouse');
		$status=$admin->where($map)->find();
		$status2=$admin->where(array('name'=>$data['name']))->find();
		if($status2){
			$return['status']=false;
			$return['message']="仓库名称已经注册过了，请换一个仓库名称";
			$this->ajaxReturn($return);
		}
		// echo $admin->getlastsql();
		// die;
		if(!$status){
				if($admin->where("nick_name='".$username."'")->count()>=1){
					$result['message']='手机号已经注册过了！';
					$result['status']=false;
					$this->ajaxReturn($result);
				}
				if($admin->where("username='".$nick_name."'")->count()>=1){
					$result['message']='昵称已经注册过了！';
					$result['status']=false;
					$this->ajaxReturn($result);
				}
				if($admin->where("nick_name='".$nick_name."'")->count()>=1){
					$result['message']='昵称已经注册过了！';
					$result['status']=false;
					$this->ajaxReturn($result);
				}
				$data['username']=$map['username'];
				//创建数据库 事务会自动提交
				$dbName="tzwms_".$data['username'];//数据库名称 "d_+手机号"
				
				$Model = M();
				$res2 = $Model->query('create database ' . $dbName);

				if($res2 === false){
					$result['message']='生成数据失败！';
					$result['status']=false;
					$this->ajaxReturn($result);
				}else{
					//导入基础表
					/*exec('cd Backup & mysql -u' . C('DB_USER') . ' -p' . C('DB_PWD') . ' ' . $dbName . ' < base.sql',$output,$return);
					if($return != 0){
						//记录日志
						Think_Log::write("创建数据库 $dbName 出错，注册用户" . $data['Mobile'] . $data['RealName']);
						
						echo '注册失败，请重试';
						exit(0);
					}*/
					
					//使用读取写入方式导入
					require_once('./Apps/Admin/Common/DBManage.class.php');
					$db = new \DBManage(C('DB_HOST'), C('DB_USER'), C('DB_PWD'), $dbName , 'utf8' );
					
					//输出缓存
					ob_start();
					//导入
					$db->restore('./data/hcf.sql');
					
					/*
					 * 同步企业用户数据库中用户信息与用户数据库中管理员信息
					 * 兼容原有数据表设计 不影响视图中的信息查询
					 */
					$connstr = C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . $dbName;
					$AuthUser = M('AuthUser','tz_',$connstr);
					$AuthGroupAccess = M('AuthGroupAccess','tz_',$connstr);
					$AuthGroup = M('AuthGroup','tz_',$connstr);
					$uid=$AuthUser->add(array('username' => $data['username'], 'password' => $data['password']));
					$AuthUser->where(array('username'=>$data['username']))->setField('uid',1);//更新注册账号的uid,默认为超级管理员
					
					$AuthGroup_data['id']=1;
					$AuthGroup_data['title']='超级管理员';
					$AuthGroup_data['status']=1;
					$AuthGroup_data['describe']='拥有最大权限';
					$AuthGroup->add($AuthGroup_data);//添加超级管理员角色

					$AuthGroupAccess->add(array('uid'=>1,'group_id'=>1));
					//清空缓冲
					ob_end_clean();
					
					$data['db_name']=$dbName;
					$res=$admin->add($data);
					if($res){
						// session('username',$data['username']);
						// session('warehouse_code',$data['warehouse_code']);
						// session('uid',$uid);
						// session('logintime',$data['lastlogintime']);
						$result['message']='注册成功！';
						$result['status']=true;
						$this->ajaxReturn($result);
					}else{
						$result['message']='注册失败！';
						$result['status']=false;
						$this->ajaxReturn($result);
					}
				}
				
			
		}else{
			$result['message']='手机已经注册过了！';
			$result['status']=false;
			$this->ajaxReturn($result);
		}
	}
	
	public function _empty(){
        $this->error('你请求的页面不存在!!');
    }
	
	/*
	 *获取数据库配置
     */
    public function db_config(){
		
		$info=M('Warehouse')->where(array('warehouse_code'=>session('warehouse_code')))->find();//获取配置表中对应域名的id
		// echo M()->getlastsql();
		// dump($info);
		if($info){  //天众数据库库配置
			!empty($info['db_ip'])?$db_ip=$info['db_ip']:$db_ip=C('DEPOT_DB_HOST');
			!empty($info['db_name'])?$db_name=$info['db_name']:$db_name=C('DEPOT_DB_NAME');
			!empty($info['db_username'])?$db_username=$info['db_username']:$db_username=C('DEPOT_DB_USER');
			!empty($info['db_password'])?$db_password=$info['db_password']:$db_password=C('DEPOT_DB_PWD');
			!empty($info['db_port'])?$db_port=$info['db_port']:$db_port=C('DEPOT_DB_PORT');
			!empty($info['db_pre'])?$db_pre=$info['db_pre']:$db_pre=C('DEPOT_DB_PREFIX');
			
			//当前仓库数据库配置
			C('DB_DEPOT.DB_TYPE','mysql');
			C('DB_DEPOT.DB_HOST',$db_ip);
			C('DB_DEPOT.DB_NAME',$db_name);
			C('DB_DEPOT.DB_USER',$db_username);
			C('DB_DEPOT.DB_PWD',$db_password);
			C('DB_DEPOT.DB_PORT',$db_port);
			C('DB_PRS',$db_pre);
			C('DB_DEPOT.DB_CHARSET','utf8');
			
			
			//权限验证设置
			C('AUTH_CONFIG.AUTH_ON',true);
			C('AUTH_CONFIG.AUTH_TYPE',1);
			C('AUTH_CONFIG.AUTH_GROUP',C('DB_PRS').'auth_group');
			C('AUTH_CONFIG.AUTH_GROUP_ACCESS',C('DB_PRS').'auth_group_access');
			C('AUTH_CONFIG.AUTH_RULE',C('DB_PRS').'auth_rule');
			C('AUTH_CONFIG.AUTH_USER',C('DB_PRS').'auth_user');
		}
    }


}

?>